package org.xiaojl.modules.sys.controller;

import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.xiaojl.common.SessionUser;
import org.xiaojl.common.base.BaseController;
import org.xiaojl.config.shiro.PasswordHash;
import org.xiaojl.dwz.DwzAjax;
import org.xiaojl.dwz.PageBean;
import org.xiaojl.dwz.PageParam;
import org.xiaojl.modules.sys.entity.SysRole;
import org.xiaojl.modules.sys.entity.SysUser;
import org.xiaojl.modules.sys.service.SysRoleService;
import org.xiaojl.modules.sys.service.SysUserRoleService;
import org.xiaojl.modules.sys.service.SysUserService;
import org.xiaojl.utils.ToolUtil;
import org.xiaojl.utils.WebUtil;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

/**
 * <p>
 * 系统用户 前端控制器
 * </p>
 *
 * @author xiaojl
 * @since 2017-08-18
 */
@Controller
@RequestMapping("/sys/sysUser")
public class SysUserController extends BaseController{
	private static final Logger log = LoggerFactory.getLogger(SysUserController.class);
	private static final String basePagePath = "sys/user/";
	
	@Autowired
    private PasswordHash passwordHash;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	
	@RequiresPermissions("sys/sysUser/list")
	@RequestMapping("/list")
	public ModelAndView list(PageParam pageParam, SysUser user, Model model){
		try {
			PageBean<SysUser> pageBean = this.selectListPage(pageParam, user, sysUserService);
			
			model.addAttribute("pageBean", pageBean);
			model.addAttribute("pageParam", pageParam);
			model.addAttribute("entity", user);
			
			return operatePage(basePagePath+"list",model);
		} catch (Exception e) {
			log.error("查询列表数据出现异常:", e);
			return operateError("获取数据失败");
		}
	}
	
	/**
     * Ajax请求校验loginName是否唯一。
     */
	@RequestMapping("/checkLoginName")
	@ResponseBody
	public boolean checkLoginName(String loginName){
		List<SysUser> listByLoginName = sysUserService.selectList(new EntityWrapper<SysUser>().eq("loginName",loginName));
		if (ToolUtil.isNotEmpty(listByLoginName)) {
			return false;
		}
		return true;
	}
	
	@RequiresPermissions("sys/sysUser/detail")
	@RequestMapping("/detail")
	public ModelAndView detail(Model model, Long id){
		try {
			SysUser entity = sysUserService.selectById(id);
			if (ToolUtil.isEmpty(entity)) {
				return operateError("获取数据失败");
			}

			model.addAttribute("entity",entity);
			return operatePage(basePagePath+"detail",model);
		} catch (Exception e) {
			log.error("查询详情数据出现异常:", e);
			return operateError("获取数据失败");
		}
	}
	
	/**
	 * 转到添加页面 .
	 */
	@RequiresPermissions("sys/sysUser/add")
	@RequestMapping("/addUI")
	public ModelAndView addUI(Model model) {
		try {
			return operatePage(basePagePath+"add",model);
			
		} catch (Exception e) {
			log.error("进入添加页面出现异常:", e);
			return operateError("获取数据失败");
		}
	}
	
	/**
	 * 保存 .
	 */
	@RequiresPermissions("sys/sysUser/add")
	@RequestMapping("/add")
	public ModelAndView add(Model model, SysUser entity, DwzAjax dwz) {
		try {
			List<SysUser> listByLoginName = sysUserService.selectList(new EntityWrapper<SysUser>().eq("loginName",entity.getLoginName()));
			if (ToolUtil.isNotEmpty(listByLoginName)) {
				return operateError("登录名【" + entity.getLoginName() + "】已存在");
			}
			
			List<SysUser> listByRealName = sysUserService.selectList(new EntityWrapper<SysUser>().eq("realName",entity.getRealName()));
			if (ToolUtil.isNotEmpty(listByRealName)) {
				return operateError("真实用户名【" + entity.getRealName() + "】已存在");
			}

			entity.setCreateBy(WebUtil.getSessionUser(request).getSysUser().getId());
			String salt = ToolUtil.getUUId();
	        String pwd = passwordHash.toHex(entity.getLoginPwd(), salt);
	        entity.setLoginPwd(pwd);
	        entity.setSalt(salt);
			sysUserService.insert(entity);
			return operateSuccess(dwz);
		} catch (Exception e) {
			log.error("添加数据出现异常:", e);
			return operateError("保存数据失败");
		}
	}
	
	/**
	 * 转到修改页面 .
	 */
	@RequiresPermissions("sys/sysUser/edit")
	@RequestMapping("/editUI")
	public ModelAndView editUI(Model model, Long id) {
		try {
			SysUser entity = sysUserService.selectById(id);
			if (ToolUtil.isEmpty(entity)) {
				return operateError("获取数据失败");
			}

			model.addAttribute("entity",entity);
			return operatePage(basePagePath+"edit",model);
		} catch (Exception e) {
			log.error("进入编辑页面时，获取数据出现异常:id="+id, e);
			return operateError("获取数据失败");
		}
	}
	
	/**
	 * 保存修改后的信息 .
	 * 
	 */
	@RequiresPermissions("sys/sysUser/edit")
	@RequestMapping("/edit")
	public ModelAndView edit(SysUser entity, DwzAjax dwz) {
		try {
			Long id = entity.getId();

			SysUser sysUser = sysUserService.selectById(id);
			if (ToolUtil.isEmpty(sysUser)) {
				return operateError("无法获取要修改的数据");
			}
			
			if(!entity.getLoginName().equals(sysUser.getLoginName())){
				List<SysUser> listByLoginName = sysUserService.selectList(new EntityWrapper<SysUser>().eq("loginName",entity.getLoginName()));
				if (ToolUtil.isNotEmpty(listByLoginName)) {
					return operateError("登录名【" + entity.getLoginName() + "】已存在");
				}
			}
			if(!entity.getRealName().equals(sysUser.getRealName())){
				List<SysUser> listByRealName = sysUserService.selectList(new EntityWrapper<SysUser>().eq("realName",entity.getRealName()));
				if (ToolUtil.isNotEmpty(listByRealName)) {
					return operateError("真实用户名【" + entity.getRealName() + "】已存在");
				}
			}
			
			sysUserService.updateById(entity);
			return operateSuccess(dwz);
		} catch (Exception e) {
			log.error("保存修改数据出现异常:", e);
			return operateError("保存失败");
		}
	}
	
	
	/**
	 * 删除
	 */
	@RequiresPermissions("sys/sysUser/delete")
	@RequestMapping("/delete")
	public ModelAndView delete(Long id, DwzAjax dwz) {
		try {
			SysUser sysUser = sysUserService.selectById(id);
			if (ToolUtil.isEmpty(sysUser)) {
				return operateError("无法获取要删除的数据");
			}
			
			//级联删除
			sysUserService.deleteWithCascade(id);
			return operateSuccess(dwz);
		} catch (Exception e) {
			log.error("删除出现异常:id="+id, e);
			return operateError("删除失败");
		}
	}
	
	
	/**
	 * 转到分配角色页面 .
	 */
	@RequiresPermissions("sys/sysUser/assignRole")
	@RequestMapping("/assignRoleUI")
	public ModelAndView assignRoleUI(Model model, Long id) {
		try {
			SysUser entity = sysUserService.selectById(id);
			if (ToolUtil.isEmpty(entity)) {
				return operateError("获取数据失败");
			}
			
			String roleIds = sysUserRoleService.selectRoleIdsByUserId(id);
			List<SysRole> roleList = sysRoleService.selectList(
					new EntityWrapper<SysRole>().eq("delFlag", 0)
					.orderBy("createTime", true)
					);
			
			if(ToolUtil.isNotEmpty(roleIds) && ToolUtil.isNotEmpty(roleList)){
				for(SysRole r: roleList){
					if(roleIds.indexOf(r.getId()+"")>-1){
						r.setStatus(1);
					}else{
						r.setStatus(0);
					}
				}
			}
			model.addAttribute("roleList", roleList);
			model.addAttribute("entity",entity);
			return operatePage(basePagePath+"assignRole",model);
		} catch (Exception e) {
			log.error("进入编辑页面时，获取数据出现异常:id="+id, e);
			return operateError("获取数据失败");
		}
	}
	
	/**
	 * 保存角色分配.
	 */
	@RequiresPermissions("sys/sysUser/assignRole")
	@RequestMapping("/assignRole")
	public ModelAndView assignRole(Long id, String selectVal, DwzAjax dwz) {
		try {
			SysUser sysUser = sysUserService.selectById(id);
			if (ToolUtil.isEmpty(sysUser)) {
				return operateError("无法获取要删除的数据");
			}
			SessionUser su = WebUtil.getSessionUser(request);
			sysUserRoleService.updateByUserId(id,selectVal,su);
			
			return operateSuccess(dwz);
		} catch (Exception e) {
			log.error("保存角色分配出现异常:id="+id, e);
			return operateError("保存角色分配失败");
		}
	}
}
